package cn.edu.scau.cmi.zhangjunming.client;

import java.util.ArrayList;

import cn.edu.scau.cmi.zhangjunming.singleton.Chairman;
import cn.edu.scau.cmi.zhangjunming.singleton.Marshal;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class SingletonClient extends Application{
    boolean onlySample = true;
    
	public static void main(String[]args) {
		launch(args);
	}
	public SingletonClient() {
		
	}

	public void start(Stage primaryStage) throws Exception {
		

		//输入窗口
		TextField textField = new TextField();
		textField.setPrefWidth(160);
		textField.setLayoutX(10);
		textField.setLayoutY(40);
		
		Label nameLabel = new Label("模式：单例模式");
		nameLabel.setLayoutX(10);
		nameLabel.setLayoutY(12);
		
		//显示信息的窗口
		TextArea textArea = new TextArea();
		textArea.setPrefWidth(600);
		textArea.setPrefHeight(400);
		textArea.setLayoutX(10);
		textArea.setLayoutY(80);
		
		//模式改变按钮
		Button changeButton = new Button("改变模式");
		changeButton.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent arg0) {
				if(onlySample) {
					nameLabel.setText("模式：多例模式");
				}
				else {
					nameLabel.setText("模式：单例模式");
				}
				onlySample = !onlySample;
			}
		});
		changeButton.setLayoutX(150);
		changeButton.setLayoutY(8);
		
		//创建按钮
		Button sureButton = new Button("创建");
		sureButton.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent arg0) {
				//String s = textField.getText();
				// textArea.clear();
				String name = textField.getText();
				if (onlySample) {
					textArea.appendText(Chairman.getInstance(name).getName() + Chairman.getInstance(name) + "\n");
				} else {
					ArrayList<Marshal> instance = Marshal.getList();

					if ((Marshal.getInstance(name)) == null) {
						textArea.appendText("已经创建十大元帅，不能再创建了");
					} else {
						if (instance.size() > 0) {
							textArea.appendText(instance.get(instance.size()-1 ).getName()
									+ instance.get(instance.size()-1 ).toString() + "\n");
						}
					}
				}
			}

		});
		sureButton.setLayoutX(180);
		sureButton.setLayoutY(40);
		
		
		Group group=new Group(sureButton,changeButton,textField,textArea,nameLabel);
		Scene scene = new Scene(group,620,550);
		
		primaryStage.setTitle("单例与多例");
		
		primaryStage.setScene(scene);
		primaryStage.show();
		
	}

}
